import Scroll from '@/components/scroll/index.vue'
import type { Ref, UnwrapRef } from 'vue'
export default function useIndex(groupRef: Ref<UnwrapRef<HTMLUListElement | null>>): {
  scrollRef: Ref<InstanceType<typeof Scroll> | null>
  indexRef: Ref<UnwrapRef<HTMLUListElement | null>>
  touchstartHandle: (e: TouchEvent) => void
  touchmoveHandle: (e: TouchEvent) => void
} {
  const touch: { y1: number; y2: number; index: number } = {
    y1: 0,
    y2: 0,
    index: 0
  }
  const scrollRef = ref<InstanceType<typeof Scroll> | null>(null)
  const indexRef = ref<HTMLUListElement | null>(null)
  function touchstartHandle(e: TouchEvent) {
    touch.y1 = e.touches[0].pageY
    touch.index = Number((e.target as HTMLElement).dataset.index)
    scrollTo(touch.index)
  }
  function touchmoveHandle(e: TouchEvent) {
    touch.y2 = e.touches[0].pageY
    const delta = Math.floor(
      (touch.y2 - touch.y1) / (indexRef.value?.children[0].clientHeight || 1)
    )
    scrollTo(touch.index + delta)
  }
  function scrollTo(index: number) {
    const groupRefVal = groupRef.value?.children
    if (groupRefVal && groupRefVal[index]) {
      scrollRef.value?.scroll?.scrollToElement(groupRefVal[index] as HTMLElement, 0, false, false)
    }
  }
  return {
    scrollRef,
    indexRef,
    touchstartHandle,
    touchmoveHandle
  }
}
